package com.rfid.emergencywarehouse;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.annotation.NonNull;

import com.rfid.emergencywarehouse.util.ScanUtil;

public class BarcodeScanner {
    Listener mListener;
    ScanUtil mScanUtil;

    public BarcodeScanner(Context context,@NonNull Listener listener) {
        mListener = listener;
        mScanUtil = new ScanUtil(context);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("onReceive");
            byte[] data = intent.getByteArrayExtra("data");
            if (data != null) {
                String barcode = new String(data).trim();
                System.out.println(barcode);
                mListener.onScanBarcode(barcode);
            }
        }
    };

    public void listenBarcode(Context context) {
        mScanUtil.setScanMode(0);
        System.out.println("listenBarcode");
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.rfid.SCAN");
        context.registerReceiver(receiver, filter);
    }

    public void releaseListenBarcode(Context context) {
        mScanUtil.setScanMode(1);
        mScanUtil.close();
        context.unregisterReceiver(receiver);
    }

    public interface Listener{
        public void onScanBarcode(String barcode);
    }
}
